﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;
using System.Xml;
using UFSoft.UBF.Service;

namespace UFIDA.U9.Cust.HWProject.CreateAPBillHead.CreateAPBilBP
{
    public class Publics
    {
        #region 将对象转换为json字符串

        /// <summary>
        /// 将对象转换为json字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string TransJsonByList(object obj)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(obj);
        }

        #endregion 将对象转换为json字符串

        #region 获取XML文档信息

        /// <summary>
        /// 获取XML文档中的key 和 secret
        /// </summary>
        /// <param name="key"></param>
        /// <param name="secret"></param>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static bool GetSRMXml(string name, out string Url)
        {
            bool bo = false;

            Url = "";
            //http://192.168.50.156/prana-clud/api/mm/addMaterialCategory
            //http://192.168.50.156/prana-cloud/api/mm/addMaterial
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "HZZFWSFLKHWU9TOSRM_ConfigFile.xml");
                XmlNode root = doc.SelectSingleNode("//SRM");
                if (name == "APBil")
                {
                    Url = (root.SelectSingleNode("APbilURL")).InnerText;                  
                }
                bo = true;
            }
            catch (Exception ex)
            {
                bo = false;
            }

            return bo;
        }

        #endregion 获取XML文档信息

        #region Post请求

        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="content"></param>
        /// <param name="errmsg"></param>
        /// <returns></returns>
        public static string Post(string url, string content,out string errmsg)
        {
            string result = "";
            try
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.ContentType = "application/json";
                req.Timeout = 50000;
                req.Headers.Add("key", "9f1904c4");
                req.Headers.Add("secret", "e1e2612180564886946e443d93768e70");
                req.ServicePoint.Expect100Continue = false;

                #region 添加Post 参数

                byte[] data = Encoding.UTF8.GetBytes(content);

                req.ContentLength = data.Length;

                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }

                #endregion 添加Post 参数

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

                Stream stream = resp.GetResponseStream();

                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
                errmsg = "";
            }
            catch (Exception ex)
            {
                errmsg = ex.Message;
                WriteLogFile("SRM接口调用失败，响应结果：" + result + "，错误信息：" + errmsg);
            }
            return result;
        }

        #endregion Post请求

/// <summary>
/// 获取SRM token
/// </summary>
/// <param name="url"></param>
/// <param name="jsonContent"></param>
/// <param name="errmsg"></param>
/// <returns></returns>

        public static string StartCalling(string url, string JsonStr)
        {
            string msg = "";
            string errmsg = "";
            string content = "";

            WriteLogFile("SRM接口调用，URL：" + url + "，请求参数：" + JsonStr);

            content = Post(url, JsonStr, out errmsg);
            if (string.IsNullOrEmpty(errmsg))
            {
                //JObject jObject = (JObject)JsonConvert.DeserializeObject(content);
                Return Return = JsonConvert.DeserializeObject<Return>(content);

                //Return Return = JsonConvert.DeserializeObject<Return>(jObject["data"].ToString());
                if (Return != null)
                {
                    if (Return.Result.Code != "200")
                    {
                        msg = Return.Result.Message;
                    }
                }
            }
            return msg;
        }
        #region 入参
        public  class InData
        {
            /// <summary>
            /// 业务账号
            /// </summary>
            public string bus_account { get; set; }
            /// <summary>
            /// 接口编码
            /// </summary>
            public string interface_code { get; set; }
            /// <summary>
            /// 请求体
            /// </summary>
            public List<body> result { get; set; }
            /// <summary>
            /// 业务账号
            /// </summary>
            public string success { get; set; }
            /// <summary>
            /// 业务账号
            /// </summary>
            public string timestamp { get; set; }
        }

        public class body
        {
            public string billNo { get; set; }
            public string supplierCode { get; set; }
            public string currencyCode { get; set; }
            public string amount { get; set; }
            public string taxAmount { get; set; }
            public string noTaxAmount { get; set; }
            public string billDate { get; set; }
            public string remark { get; set; }
        }

        #endregion

        #region 返回信息

        public  class Return
        {
            [JsonProperty("code")]
            public string Code { get; set; }

            [JsonProperty("message")]
            public string Message { get; set; }

            [JsonProperty("result")]
            public ResultContainer Result { get; set; }

            [JsonProperty("success")]
            public bool Success { get; set; }

            [JsonProperty("timestamp")]
            public long Timestamp { get; set; }
        }

        public class ResultContainer
        {
            [JsonProperty("result")]
            public result Result { get; set; }

            [JsonProperty("code")]
            public string Code { get; set; }

            [JsonProperty("success")]
            public bool Success { get; set; }

            [JsonProperty("message")]
            public string Message { get; set; }

            [JsonProperty("timestamp")]
            public long Timestamp { get; set; }
        }

        public class result
        {
            [JsonProperty("result")]
            public string Result { get; set; }

            [JsonProperty("code")]
            public string Code { get; set; }

            [JsonProperty("success")]
            public bool Success { get; set; }

            [JsonProperty("billNo")]
            public string BillNo { get; set; }
        }


        #endregion 返回信息

        public static string GetValueOrDefault(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return "";
            }
            return value;
        }

        //public static string GetValueOrDefault(string value)
        //{
        //    if (string.IsNullOrEmpty(value)||value=="null")
        //    {
        //       throw new Exception("必填字段不能为空");
        //    }
        //    return value;
        //}

        #region 日志记录
        public static void WriteLogFile(string input)
        {
            string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            string Onepath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\SRM集成开发日志";

            string Twopath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\SRM集成开发日志" + "\\" + "U9ToSRM";

            string Scrrenpath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\SRM集成开发日志" + "\\" + "U9ToSRM" + "\\" + "BE";

            string Fourpath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\SRM集成开发日志" + "\\" + "U9ToSRM" + "\\" + "BE" + "\\" + DateTime.Now.Date.ToShortDateString();
            //指定日志文件的目录
            string fname = Fourpath + "\\log.txt";

            if (!Directory.Exists(Onepath))
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(Onepath);
                directoryInfo.Create();
            }

            if (!Directory.Exists(Twopath))
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(Twopath);
                directoryInfo.Create();
            }

            if (!Directory.Exists(Scrrenpath))
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(Scrrenpath);
                directoryInfo.Create();
            }

            if (!Directory.Exists(Fourpath))
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(Fourpath);
                directoryInfo.Create();
            }
            //定义文件信息对象
            FileInfo finfo = new FileInfo(fname);

            if (!finfo.Exists)
            {
                FileStream fs;
                fs = File.Create(fname);
                fs.Close();
                finfo = new FileInfo(fname);
            }

            string OldName = DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();

            //文件超过5MB则重命名
            if (finfo.Length > 1024 * 1024 * 5)
            {
                File.Move(Fourpath + "\\" + "log.txt", Fourpath + "\\" + OldName + "log.txt");
            }

            using (FileStream fs = finfo.OpenWrite())
            {
                //根据上面创建的文件流创建写数据流
                StreamWriter w = new StreamWriter(fs);
                //设置写数据流的起始位置为文件流的末尾
                w.BaseStream.Seek(0, SeekOrigin.End);
                //写入当前系统时间并换行
                w.Write("{0} \n\r", DateTime.Now.ToLongDateString());
                //写入日志内容并换行
                w.Write(input + "\n\r");
                //写入------------------------------------“并换行
                w.Write("------------------------------------------------------------------------------------------------------------\n\r");
                //清空缓冲区内容，并把缓冲区内容写入基础流
                w.Flush();
                //关闭写数据流
                w.Close();
            }
        }

        #endregion
    }
}